import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useBoardStore = defineStore('board', () => {
  // 状态
  const activePboardId = ref(null)
  const activeBoardId = ref(null)

  // 设置当前选中的父板块
  const setActivePboardId = (pBoardId) => {
    activePboardId.value = pBoardId
  }

  // 设置当前选中的子板块
  const setActiveBoardId = (boardId) => {
    activeBoardId.value = boardId
  }

  // 同时设置父板块和子板块
  const setActiveBoard = (pBoardId, boardId = null) => {
    activePboardId.value = pBoardId
    activeBoardId.value = boardId
  }

  // 清空选中状态
  const clearActiveBoard = () => {
    activePboardId.value = null
    activeBoardId.value = null
  }

  // 根据路由参数更新板块状态
  const updateBoardFromRoute = (route) => {
    const { pBoardId, boardId } = route.params
    
    if (pBoardId) {
      activePboardId.value = parseInt(pBoardId)
    } else {
      activePboardId.value = null
    }
    
    if (boardId) {
      activeBoardId.value = parseInt(boardId)
    } else {
      activeBoardId.value = null
    }
  }

  return {
    // 状态
    activePboardId,
    activeBoardId,
    
    // 方法
    setActivePboardId,
    setActiveBoardId,
    setActiveBoard,
    clearActiveBoard,
    updateBoardFromRoute
  }
}, {
  // 持久化存储
  persist: true
})